package com.ruoyi.circle.dao.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.circle.dao.ICircleMemberRelationDao;
import com.ruoyi.circle.domain.CircleMemberRelation;
import com.ruoyi.circle.mapper.CircleBasicInfoMapper;
import com.ruoyi.circle.mapper.CircleMemberRelationMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

/**
 * 圈子成员关系Dao业务层处理
 * 
 * @author 区嘉盛
 * @date 2025-06-09
 */
@Repository
public class CircleMemberRelationDaoImpl extends ServiceImpl<CircleMemberRelationMapper, CircleMemberRelation> implements ICircleMemberRelationDao {
    
    @Autowired
    private CircleMemberRelationMapper circleMemberRelationMapper;
    
    @Autowired
    private CircleBasicInfoMapper circleBasicInfoMapper;

    /**
     * 添加圈子成员
     *
     * @param circleId 圈子ID
     * @param userId 用户ID
     * @param memberRole 成员角色
     * @return 结果
     */
    @Override
    public int addCircleMember(Long circleId, Long userId, Integer memberRole) {
        CircleMemberRelation relation = new CircleMemberRelation();
        relation.setCircleId(circleId);
        relation.setUserId(userId);
        relation.setMemberRole(memberRole);
        relation.setMemberStatus(1);
        relation.setJoinedTime(LocalDateTime.now());
        relation.setCreateBy(SecurityUtils.getUsername());
        relation.setCreateTime(DateUtils.getNowDate());
        int rows = circleMemberRelationMapper.insertCircleMemberRelation(relation);
        if (rows > 0) {
            updateCircleMemberCount(circleId);
        }
        return rows;
    }
    
    /**
     * 更新圈子成员数量
     *
     * @param circleId 圈子ID
     * @return 结果
     */
    private void updateCircleMemberCount(Long circleId) {
        int memberCount = circleMemberRelationMapper.selectCircleMemberCount(circleId);
        circleBasicInfoMapper.updateCircleMemberCount(circleId, memberCount);
    }
}